import { Component, Injector, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { MenuItemDto, NavigationSyncServiceProxy, GetMenuTreeOutput, MenuSynInput } from '@shared/service-proxies/service-proxies';
import { ArrayToTreeConverterService } from '@shared/utils/service/array-to-tree-converter.service';
import { TreeDataHelperService } from '@shared/utils/service/tree-data-helper.service';
import { filter as _filter,map as _map, remove as _remove } from 'lodash-es';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { TreeNode } from 'primeng/api';
import { Tree } from 'primeng/tree';
import { AddMenuComponent } from './add-menu.component';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'sync-menus-modal',
    templateUrl: './sync-menus-modal.component.html'
})
export class SyncMenusModalComponent extends AppComponentBase {
    @ViewChild('lookOverMenuItem', { static: true }) lookOverMenuItem: AddMenuComponent;
    @ViewChild('editmodal', {static: true}) modal: ModalDirective;

    @ViewChild('ptree', { static: true }) ptree: Tree;

    treeData: any;
    selectedOu: TreeNode[] = [];
    motherSite: string;
    fromLanguage: string;
    motherSiteTenantId: number;

    saving = false;

    totalUnitCount = 0;

    hasChange = false;

    private fieldMappings = [
        {
            target: 'label',
            targetFunction(item) {
                return item.displayName;
            }
        }, {
            target: 'expandedIcon',
            targetFunction(item) {
                if (item.isActive) {
                    return 'fa fa-folder-open text-warning';
                } else {
                    return 'fa fa-folder-open font-grey';
                }
            }
        },
        {
            target: 'collapsedIcon',
            targetFunction(item) {
                if (item.isActive) {
                    return 'fa fa-folder text-warning';
                } else {
                    return 'fa fa-folder font-grey';
                }
            }
        },
        {
            target: 'selectable',
            value: true
        }
    ];

    constructor(
        injector: Injector,
        private _navigationSyncService: NavigationSyncServiceProxy,
        private _arrayToTreeConverterService: ArrayToTreeConverterService,
        private _treeDataHelperService: TreeDataHelperService
    ) {
        super(injector);
    }


    show(): void {
        this.modal.show();
    }

    close(): void {
        if(this.hasChange){

        }
        this.modal.hide();
    }

    ngOnInit(): void {
        this.getTreeDataFromServer();
    }

    nodeSelect(event) {
        this.lookOverMenu(<MenuItemDto>event.node.data);

        let parentNode = this._treeDataHelperService.findParent(this.treeData, { data: { id: event.node.data.parentId } });

        while (parentNode != null) {
            this.selectedOu.push(parentNode);
            parentNode = this._treeDataHelperService.findParent(this.treeData, { data: { id: parentNode.data.parentId } });
        }
    }

    onNodeUnselect(event) {
        let childrenNodes = this._treeDataHelperService.findChildren(this.treeData, { data: { parentId: event.node.data.id } });
        childrenNodes.push(event.node.data.id);
        _remove(this.selectedOu, x => childrenNodes.indexOf(x.data.id) !== -1);
    }

    private lookOverMenu(event: MenuItemDto):void{
        this.lookOverMenuItem.menuItemDto = event;
    }

    private getSelectedMenus(): string[] {
        if (!this.selectedOu || !this.selectedOu.length) {
            return [];
        }

        let temps = [];
        
        this.selectedOu.forEach((val, index)=>{
            if(!val.data.id){
                return;
            }

            let existIndex = -1;
            let code = val.data.code;
            for (let i = 0; i < temps.length; i++) {
                let thisCode = temps[i].code;
                if (thisCode === code) {
                    existIndex = i;
                } else if (code.indexOf(thisCode+'.')=== 0) {
                    temps.splice(i, 1);
                    i--;
                }
            }

            if (existIndex === -1) {
                temps.push({ id: val.data.id, code: code });
            }
        });
        
        return temps.map(t=>t.id);
    }

    save(){
        this.message.confirm(this.l('ManualSyncWarningMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;

                let input = new MenuSynInput();
                input.fromLanguage = this.fromLanguage;
                input.requiredMenuItems = this.getSelectedMenus();

                this.saving = true;
                this._navigationSyncService.manualSynchorize(input)
                .pipe(finalize(() => this.saving = false))
                .subscribe(result=>{
                    this.hasChange = true;
                    this.notify.success(this.l('ManualSynchorizationSuccessfully'))
                })
            })
    }

    _filter(value) {
        this.ptree._filter(value);
    }

    reload(): void {
        this.getTreeDataFromServer();
    }

    private getTreeDataFromServer(): void {
        this._navigationSyncService.getMenuTreeFromParentSite()
         .subscribe((result: GetMenuTreeOutput) => {
            this.motherSite = result.tenantDisplayName;
            this.fromLanguage = result.motherLanguage;
            this.motherSiteTenantId = result.motherTenantId;

            this.totalUnitCount = result.items.length;
             let nodes = this._arrayToTreeConverterService.createTree(result.items,
                 'parentId',
                 'id',
                 null,
                 'children',
                 this.fieldMappings,
                 (a, b) => a.order - b.order
             );

             let newNode = {
                 data: {
                     isActive: true,
                     displayName: 'root'
                 },
                 children: nodes
             };
             this.treeData = [newNode];
             this.lookOverMenu(null);
             this.collapseAll();
        });
    }

    expandAll() {
        this._treeDataHelperService.operateTreeNode(this.treeData, (t)=>t.expanded = true);
    }

    collapseAll() {
        this._treeDataHelperService.operateTreeNode(this.treeData, (t)=>t.expanded = false);
    }
}
